package com.zhang.hadoop.flink.test3;

import com.zhang.hadoop.flink.base.Event;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zhang yufei
 * @createTime:2022/5/21 16:08
 * @description:
 */
public class TransformRichFunctionTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        List<Event> events = new ArrayList<>();
        events.add(new Event("huichao", "./yindao", 1000L));
        events.add(new Event("yanghui", "./yindao", 1000L));
        events.add(new Event("yanghui", "./gangmen", 2000L));
        events.add(new Event("yanghui", "./siwajiao", 3000L));
        events.add(new Event("yuping", "./siwajiao", 2000L));
        events.add(new Event("yuping", "./yindao", 4000L));
        events.add(new Event("yangdan", "./gangmen", 2000L));
        events.add(new Event("yangdan", "./yindao", 6000L));
        events.add(new Event("jingru", "./niaodao", 2000L));
        DataStreamSource<Event> stream = env.fromCollection(events);

        stream.map(new MyRichMapper()).print();

        env.execute();
    }

    public static class MyRichMapper extends RichMapFunction<Event, Integer> {

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            System.out.println("open生命周期被调用" + getRuntimeContext().getIndexOfThisSubtask() + "号任务启动");
        }

        @Override
        public Integer map(Event event) throws Exception {
            return event.url.length();
        }

        @Override
        public void close() throws Exception {
            super.close();
            System.out.println("close生命周期被调用" + getRuntimeContext().getIndexOfThisSubtask() + "号任务启动");
        }
    }
}
